<template>
    <div class="folder-Browser">
        <pui-dialog :maskClick="false" :title="props.title" v-model="componentRef.dialogVisible" :animate="props.animate" width="450px" isFooter @onClose="closeDialog">
            <template #content>
                <div class="folder-content">
                    <div class="folder-aside">
                        <div class="folder-list">
                            <div class="folder-item" @dblclick="backLastDirectory()" v-if="!componentRef.lastPath || componentRef.lastPath === ''">
                                <pui-icon size="large" color="#FFCA28" name="dakai"></pui-icon>
                                · · ·
                            </div>
                            <!-- <div :class="['folder-item', i === componentRef.sideCurIndex && 'active-item']" v-for="(item, i) in componentRef.sideList" :key="i" @click="onSideItemClickHandle(item, i)">
                                <pui-icon size="large" color="#FFCA28" name="dakai"></pui-icon>
                                <span class="name ellipsis-1">{{ item.name }}</span>
                            </div> -->
                        </div>
                    </div>
                    <div class="folder">
                        <p>名称</p>
                        <div class="folder-list">
                            <div :class="['folder-item', i === componentRef.dirCurIndex && 'active-item']" :key="i" v-for="(item, i) in componentRef.contentList" @dblclick="(item.type === 0 || item.type === 2) && _dblclickHandle(item.path)" @click="_singleClickHandle(item, i)" @keyDown.delete="onDeleteClickHandle">
                                <pui-icon size="large" color="#FFCA28" :name="(item.type === 0 || item.type === 2)? 'dakai' : 'xinjian'"></pui-icon>
                                <span class="name ellipsis-1">{{ item.name }}</span>
                            </div>
                            <div class="nodata" v-if="componentRef.contentList.length === 0">--  此文件为空  --</div>
                        </div>
                    </div>
                </div>
            </template>
            <template #footer>
                <pui-button type="primary" @click="onNewProjectClickHandle">创建文件夹</pui-button>
                <div>
                    <pui-button @click="closeDialog">取消</pui-button>
                    <pui-button type="primary" @click="onSubmitHandle">确定</pui-button>
                </div>
            </template>
        </pui-dialog>
    </div>
    <NewDirectory @onSuccess="onNewDirectorySuccess" ref="NewDirectoryRef"></NewDirectory>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import store from '@/store'
export default defineComponent({
    name: 'FolderBrowser'
})
</script>
<script lang="ts" setup>
import { nextTick, onMounted, reactive, getCurrentInstance, watch } from 'vue'
import upath from 'upath'
import { projectService as projectApi } from '@/services/phot_client/client'
import NewDirectory from './newDirectory.vue'
const { proxy } = getCurrentInstance() as any
const {ipcRenderer} = require('electron')
const nodeDiskInfo = require('node-disk-info')
const props = defineProps({
    title: {
        type: String,
        default: '浏览文件夹'
    },
    animate: {
        type: String,
        default: 'fade'
    },
    root: {
        type: String,
        default: './photlab'
    }
})
const emit = defineEmits({
    'onSubmit': (val: any) => {}
})
let timer: any = null
const componentRef = reactive({
    dialogVisible: false,
    sideList: [],
    contentList: [],
    nowPath: '',
    directoryPath: './photlab',
    dirctoryName: '',
    sideCurIndex: null,
    dirCurIndex: null,
    selectedFile: {},
    listType: null
}) as any
const init = async (type: any = null) => {
    componentRef.listType = type
    componentRef.sideCurIndex = null
    componentRef.dirCurIndex = null
    componentRef.contentList = []
    componentRef.sideList = []
    componentRef.dialogVisible = true
    await nextTick()
    // if (type !== 'windows') {
        await getDirectoryList('./photlab')
    // } else {
        const diskinfo = await getDiskinfo()
        // console.log(diskinfo)
        diskinfo?.diskList.map((item: any) => {
            componentRef.sideList.push({
                name: item.mounted,
                path: item.mounted + '\\'
            })
        })
    // }
}
const closeDialog = () => {
    componentRef.dialogVisible = false
}

const getDiskinfo = async () => {
    const base = __dirname.substring(0,2)
    const diskList = [] as any
    try {
        const disks = nodeDiskInfo.getDiskInfoSync()
        for (const disk of disks) {
            diskList.push({
                filesystem: disk.filesystem,
                blocks: disk.blocks,
                used: disk.used,
                available: disk.available,
                capacity: disk.capacity,
                mounted: disk.mounted
            })
        }
        return {
            base,
            diskList
        }
    } catch (e) {
        console.error(e)
    }
}
const getDirectoryList = async (path = props.root) => {
    //   DIRECTORY = 0,
    //   COMPONENT = 1,
    //   PROJECT = 2,
    //   GRAPH = 3,
    //   GRID = 4,
    //   CONFIG = 5,
    //   OTHER = 6,
    componentRef.nowPath = path
    // console.log(path)
    await projectApi.openDirectory(path).then((res: any) => {
        // console.log(res)
        // componentRef.sideCurIndex = 0
        // componentRef.sideList = []
        componentRef.contentList = []
        // if (path === './') {
        res.map((item: any) => {
            if (item.name !== 'examples') {
                if (componentRef.listType === 'new graph' && (item.type === 0 || item.type === 2)) {
                    componentRef.contentList.push(item)
                }
                if (componentRef.listType === 'new grid' && (item.type === 0)) {
                    componentRef.contentList.push(item)
                }
                if (componentRef.listType === 'open graph' && (item.type === 0 || item.type === 2 || item.type === 3)) {
                    componentRef.contentList.push(item)
                }
                if (componentRef.listType === 'open grid' && (item.type === 0 || item.type === 4)) {
                    componentRef.contentList.push(item)
                }
                if (componentRef.listType === 'windows' && item.type === 0) {
                    componentRef.contentList.push(item)
                }
                if (!componentRef.listType) {
                    componentRef.contentList.push(item)
                }
            }
        })
        // } else {
        //     res.map((item: any) => {
        //         if (item.type === 0 || item.type === 2) {
        //             componentRef.sideList.push(item)
        //         }
        //     })
        // }
        // if (componentRef.sideList.length > 0) {
        //     fileListFromDirectory(componentRef.sideList[0].path)
        // }
    })
    .catch((err: any) => {
        console.log(err)
    })
}
const fileListFromDirectory = async (path: string) => {
    // console.log(path)
    componentRef.contentList = []
    await projectApi.openDirectory(path).then((res: any) => {
        // console.log(res)
        res.map((item: any) => {
            componentRef.contentList.push(item)
        })
    }).catch((err: any) => {
        console.log(err)
    })
}
const backLastDirectory = async () => {
    componentRef.nowPath = upath.normalizeSafe(componentRef.nowPath)
    if (componentRef.nowPath === './photlab') {
        componentRef.dirCurIndex = null
        componentRef.sideCurIndex = null
        componentRef.sideList = []
        componentRef.directoryPath = './photlab'
        await getDirectoryList()
        return
    }
    const lastIndex = componentRef.nowPath.lastIndexOf('/')
    componentRef.dirCurIndex = null
    componentRef.sideCurIndex = null
    console.log(lastIndex)
    console.log(componentRef.nowPath)
    console.log(componentRef.nowPath.substring(0, lastIndex))
    getDirectoryList(componentRef.nowPath.substring(0, lastIndex))
}
const onSideItemClickHandle = async (item: any, index: Number) => {
    projectApi.openDirectory(item.path)
    // console.log(item)
    if (componentRef.sideCurIndex === index) return
    componentRef.directoryPath = item.path
    componentRef.sideCurIndex = index
    componentRef.dirCurIndex = null
    componentRef.selectedFile = item
    await getDirectoryList(item.path)
}
const onNewProjectClickHandle = async () => {
    proxy.$refs.NewDirectoryRef.init(componentRef.nowPath)
}
const _singleClickHandle = (item: any, i: Number) => {
    // if (timer) {
    //     clearTimeout(timer)
    //     timer = null
    // }
    // timer = setTimeout(() => {
    //     console.log('single')
    //     selectDirectory(item, i)
    // }, 500)
    selectDirectory(item, i)
}
const _dblclickHandle = async (path: string) => {
    // if (timer) {
    //     clearTimeout(timer)
    //     timer = null
    // }
    // console.log('dbl')
    await getDirectoryList(path)
    componentRef.dirCurIndex = null
    // fileListFromDirectory(path)
}
const selectDirectory = (item: any, i: Number) => {
    componentRef.dirCurIndex = i
    
    componentRef.directoryPath = item.path
    if (item.type !== 0) {
        componentRef.selectedFile = item
    }
    // console.log('root:', componentRef.nowPath)
    // console.log('directory:', componentRef.directoryPath)
}
const onNewDirectorySuccess = async (e: any) => {
    if (componentRef.nowPath === './photlab') {
        await getDirectoryList()
        return
    }
    await getDirectoryList(componentRef.nowPath)
}
const onSubmitHandle = () => {
    // console.log('directoryPath:',componentRef.directoryPath)
    // console.log('nowPath:',componentRef.nowPath)
    emit('onSubmit', {path: componentRef.directoryPath, file: componentRef.selectedFile})
    closeDialog()
}
const onDeleteClickHandle = async () => {
    // console.log(componentRef.nowPath)
    if (!componentRef.dirCurIndex || !componentRef.nowPath || componentRef.nowPath === '' || componentRef.nowPath === './photlab') return
    await deleteDirctory()
    await getDirectoryList(componentRef.nowPath)
    componentRef.sideCurIndex = null
    componentRef.dirCurIndex = null
}
const deleteDirctory = async () => {
    await projectApi.deleteFile(componentRef.directoryPath).then((res: any) => {
    }).catch((err: any) => {
        console.log(err)
    })
}
onMounted(() => {
    // ipcRenderer.on('Delete', () => {
    //     onDeleteClickHandle()
    // })
})
defineExpose({
    init
})
</script>
<style lang="scss">
@import './fileStyle.scss';
</style>